package demo1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：黄淼淳
 * @date ：2021/12/12 20:50
 * @description：
 */
public class ConditionDemo {
    public static void main(String[] args) {
        Print print = new Print();
        new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++)
                    print.print10();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "张三").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++)
                    print.print15();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "李四").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++)
                    print.print5();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "王五").start();
    }
}


class Print {
    private int flag = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 1)
                condition1.await();
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + (i + 1));
            }
            flag = 2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 2)
                condition2.await();
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + (i + 1));
            }
            flag = 3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 3)
                condition3.await();
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + (i + 1));
            }
            flag = 1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}